package com.alibaba.citrus.ots.sales.plan.facade.service.setting;


import com.alibaba.citrus.ots.common.exception.FacadeException;
import com.alibaba.citrus.ots.sales.plan.api.setting.EmployeeAuthorityIsolationQueryService;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.EmployeeAuthoritysolationRequest;
import com.alibaba.citrus.ots.sales.plan.sdo.EmployeeAuthoritysolationSDO;
import com.alibaba.cz.base.tool.message.ErrorMessage;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.otsplatformenhance.enums.OrganizationTypeEnum;
import com.epoch.app.otsplatformenhance.model.dto.GetLoginEmployOrganizationPermissionsRequest;
import com.epoch.app.otsplatformenhance.sdo.OrganizationSDO;
import com.epoch.app.otsplatformenhance.service.OtsPlatformEnhanceService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class EmployeeAuthorityIsolationQueryServiceImpl implements EmployeeAuthorityIsolationQueryService {


    @Resource
    OtsPlatformEnhanceService otsPlatformEnhanceService;

    @Override
    public Result<List<EmployeeAuthoritysolationSDO>> queryEmpleeAuthoritysolation(EmployeeAuthoritysolationRequest request) {
        ///判断当前是否存在登陆人
        if (Strings.isBlank(request.getRelatedOrganizationId())) {
            throw new FacadeException("OTS-01-001-01-15-021");
        }

        //判断参数是否为空
        if (Strings.isBlank(request.getId())) {
            throw new FacadeException("OTS-05-001-10-16-028");
        }

        //当 当前登陆人type为 100 或101时  说明是蒙牛集团或者是常温事业部的人 全部能看见
        if (request.getType().equals("100") || request.getType().equals("101")) {
            return Result.success(request.getAuthoritysolationSDOList());
        }

        //获取当前登录人的  向上组织
        Result<List<OrganizationSDO>> upwardOrganizationSDO = otsPlatformEnhanceService.getLoginEmployOrganizationPermissions(GetLoginEmployOrganizationPermissionsRequest.builder().type(102).build());
        if (CollectionUtils.isEmpty(upwardOrganizationSDO.getResult())) {
            throw new FacadeException("OTS-01-001-01-15-021");
        }
        OrganizationSDO organizationSDO = upwardOrganizationSDO.getResult().get(0);
        String id = organizationSDO.getId();
        String parentId = organizationSDO.getParentId();
        List<EmployeeAuthoritysolationSDO> collect = request.getAuthoritysolationSDOList().stream().filter(i -> i.getId().equals(id)).collect(Collectors.toList());

        if (parentId.equals(request.getId())) {
            return Result.success(collect);
        }

        return Result.success(request.getAuthoritysolationSDOList());
    }
}
